package com.wen.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.wen.yygh.oss.service.FileService;
import com.wen.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author Wenjl
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {

        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;

        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRET;

        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //避免图片名称重复需要在前面加上uuid
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileName = uuid + fileName;
            //创建日期文件夹
            String dateUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = dateUrl + "/" + fileName;
            ossClient.putObject(bucketName, fileName, inputStream);
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
}
